package com.slipper.system.handler;

import java.net.SocketTimeoutException;

import javax.servlet.http.HttpServletResponse;

import com.slipper.common.exception.NotLoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.slipper.common.exception.ForbiddenException;
import com.slipper.common.util.ResultUtil;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestController
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    @ExceptionHandler(value = Throwable.class)
    public String exceptionHandler(HttpServletResponse response, Exception e) {
        Throwable throwable = e;

        if (throwable instanceof NotLoginException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 未登录
        } else if (throwable instanceof ForbiddenException) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 拒绝访问
        } else if (throwable instanceof NoHandlerFoundException) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 找不到资源
        } else if (throwable instanceof SocketTimeoutException) {
            response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); // 请求超时
        } else if (throwable != null) {
            throwable = e.getCause() != null ? e.getCause() : e;
        }
        
        logger.error("调用发生异常！", throwable);
        return ResultUtil.toErrorJson(throwable == null || throwable.getMessage() == null
                ? "未知错误！" : throwable.getMessage());
    }

    @RequestMapping("/error/notLogin")
    public String notLoginError(HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 拒绝访问
        return ResultUtil.toErrorJson("未登录！");
    }

    @RequestMapping("/error/forbidden")
    public String forbiddenError(HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 拒绝访问
        return ResultUtil.toErrorJson("权限不足！");
    }
}